<template>
  <div class="search-container">
    <!-- 居中标题 -->
    <h2 class="page-title">二手房、新房、租房</h2>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <input
        type="text"
        v-model="searchKey"
        placeholder="请输入房源标题搜索"
        class="search-input"
      />
      <button @click="handleSearch" class="search-btn">搜索</button>
    </div>

    <!-- 搜索结果 -->
    <div v-if="searchResults.length > 0" class="result-list">
      <h3 class="result-title">搜索结果（{{ searchResults.length }}条）</h3>
      <ul>
        <li
          v-for="item in searchResults"
          :key="item._id"
          class="result-item"
        >
          <div class="item-header">
            <span class="item-name" v-html="item._source.title"></span>
            <span class="item-type">状态：{{ item._source.status }}</span>
          </div>
          <div class="item-info">
            <p>id:  {{ item._id }}</p>
            <p>描述：{{ item._source.description }}</p>
            <p>地址：{{ item._source.address }}</p>
            <p>城市：{{ item._source.city }}</p>
            <p>区域：{{ item._source.district }}</p>
            <p>租金：{{ item._source.price }}元</p>
            <p>联系人：{{ item._source.contact }}</p>
            <p>电话：{{ item._source.phone }}</p>
            <p>发布时间：{{ item._source.time }}</p>
            <div class="item-btn">
              <el-button type="primary" @click="handleClick(item._source.phone)">联系</el-button>
            </div>
            <div class="item-btn">
              <el-button type="success" @click="goToOrder">预约看房</el-button>
            </div>
            <div class="item-btn">
              <el-button type="warning" @click="goToDetail(item._id)">查看详情</el-button>
            </div>
            <div class="item-btn"></div>
          </div>
        </li>
      </ul>
    </div>

    <!-- 无结果提示 -->
    <div v-else-if="isSearching" class="no-result">正在搜索...</div>
    <div v-else-if="searchKey && !searchResults.length" class="no-result">
      未找到匹配的房源信息
    </div>
  </div>
</template>


<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router'; // 引入路由钩子
import http from "@/http/index.js";

const router = useRouter(); // 初始化路由实例
const searchKey = ref('');
const searchResults = ref([]);
const isSearching = ref(false);

const handleSearch = async () => {
  if (!searchKey.value.trim()) return;

  isSearching.value = true;
  try {
    const response = await http.get('/users/house/search/', {
      params: {
        title: searchKey.value.trim()
      }
    });

    if (response.data.code === 200) {
      // 确保返回数据包含正确的_id字段
      searchResults.value = response.data.data.map(hit => ({
        _id: hit._id, // 假设接口返回的房源ID字段为_id
        _source: hit._source
      }));
    }
  } catch (error) {
    console.error('搜索失败:', error);
    alert('搜索过程中出现错误，请重试');
  } finally {
    isSearching.value = false;
  }
};

onMounted(() => {
  window.addEventListener('keypress', (e) => {
    if (e.key === 'Enter') handleSearch();
  });
});

const goBack = () => {
  // 使用路由返回上一页（更推荐的方式）
  router.go(-1);
  // 或者指定具体路由
  // router.push('/');
};


// 修改跳转到详情页面的方法，确保使用正确的路由参数
const goToDetail = (id) => {
  router.push({
    path: '/house-detail', // 确保路由配置中存在该路径
    query: { id: id } // 参数名需与目标页面接收的参数一致（通常为id）
  });
  // 可选：记录用户浏览行为（如果有需要）
  // recordHouseView(id);
};





</script>



<style scoped>












.search-container {
  max-width: 800px;
  margin: 50px auto;
  padding: 20px;
  font-family: 'Arial', sans-serif;
}

.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 30px;
}

.search-input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
}

.search-btn {
  padding: 10px 20px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s;
}

.search-btn:hover {
  background-color: #3eaf7c;
}

.result-title {
  color: #333;
  margin-bottom: 20px;
  border-bottom: 2px solid #eee;
  padding-bottom: 5px;
}

.result-list ul {
  list-style: none;
  padding: 0;
}

.result-item {
  padding: 15px;
  margin-bottom: 15px;
  border: 1px solid #eee;
  border-radius: 4px;
  background-color: #f9f9f9;
  transition: transform 0.2s;
}

.result-item:hover {
  transform: translateX(5px);
  box-shadow: 0 2px 5px rgba(0,0,0,0.05);
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.item-name {
  font-size: 1.2em;
  font-weight: bold;
  color: #42b983;
}

.item-type {
  color: #666;
  font-size: 0.9em;
}

.no-result {
  color: #666;
  text-align: center;
  margin-top: 20px;
}

/* 标签组容器 */
.tag-group {
  display: flex;          /* 使用弹性布局 */
  justify-content: center; /* 子元素水平居中 */
  align-items: center;     /* 子元素垂直居中 */
  margin: 20px 0 30px;     /* 上下间距 */
  gap: 12px;              /* 标签间距 */
}

/* 单个标签样式 */
.tag {
  padding: 8px 20px;       /* 内边距 */
  border: 1px solid #ddd;  /* 边框 */
  border-radius: 20px;     /* 圆角 */
  font-size: 16px;         /* 字体大小 */
  color: #333;             /* 文字颜色 */
  cursor: pointer;         /* 鼠标样式 */
  transition: all 0.3s;    /* 过渡动画 */
}

/* 选中状态样式 */
.tag.active {
  background-color: #42b983; /* 背景色 */
  color: white;              /* 文字颜色 */
  border-color: #42b983;     /* 边框颜色 */
  box-shadow: 0 2px 5px rgba(66, 185, 131, 0.2); /* 阴影 */
}

/* 优化标题样式（可选） */
.page-title {
  text-align: center;
  margin: 30px 0 10px;
  font-size: 24px;
  font-weight: 500;
  color: #2c3e50;
}


</style>